package ai.people.netmon.warning.service.impl;

import ai.people.core.feign.api.oss.OssFeignClient;
import ai.people.core.grpc.lib.es.*;
import ai.people.core.grpc.utils.ProtoJsonUtil;
import ai.people.core.security.support.RequestHolderUtil;
import ai.people.core.web.util.FileUtil;
import ai.people.netmon.framework.businessenum.warning.WarningExportDownloadStateEnum;
import ai.people.netmon.framework.businessenum.warning.WarningExportDocumentTypeEnum;
import ai.people.netmon.framework.businessenum.warning.WarningExportTypeEnum;
import ai.people.netmon.framework.domain.oss.vo.UploadVO;
import ai.people.netmon.framework.domain.warning.entity.WarningExport;
import ai.people.netmon.framework.domain.warning.request.WarningInfoExportRequest;
import ai.people.netmon.framework.domain.warning.vo.WarningExportListDataVO;
import ai.people.netmon.framework.exception.enums.CommonEnum;
import ai.people.netmon.framework.model.request.PageKeyWordsRequest;
import ai.people.netmon.framework.model.response.PageResponse;
import ai.people.netmon.framework.model.response.Result;
import ai.people.netmon.warning.entity.WarningInfoExportEntity;
import ai.people.netmon.warning.mapper.WarningExportMapper;
import ai.people.netmon.warning.service.WarningExportService;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.protobuf.Message;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ligua
 * @description 针对表【warning_export(预警导出表)】的数据库操作Service实现
 * @createDate 2022-07-28 17:50:38
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WarningExportServiceImpl extends ServiceImpl<WarningExportMapper, WarningExport>
        implements WarningExportService {


    private final OssFeignClient ossFeignClient;

    private final WarningExportMapper warningExportMapper;

    @GrpcClient(value = "NM-SERVICE-SEARCH-MSG")
    private BaseSearchServiceGrpc.BaseSearchServiceBlockingStub searchServiceBlockingStub;

    /**
     * 导出记录
     *
     * @param userId              用户id
     * @param pageKeyWordsRequest 页面关键字请求
     * @return {@link PageResponse}<{@link WarningExportListDataVO}>
     */
    @Override
    public PageResponse<WarningExportListDataVO> exportRecords(PageKeyWordsRequest pageKeyWordsRequest, Long userId) {
        IPage<WarningExport> page = new Page<>(pageKeyWordsRequest.getOriginPageNo(), pageKeyWordsRequest.getPageSize());
        LambdaQueryWrapper<WarningExport> lambdaQuery = Wrappers.lambdaQuery(WarningExport.class);
        IPage<WarningExport> warningExportIPage = warningExportMapper.selectPage(page, lambdaQuery);
        List<WarningExportListDataVO> exportVOList = warningExportIPage.getRecords().stream().map(WarningExportListDataVO::build).collect(Collectors.toList());
        return PageResponse.builder(exportVOList, warningExportIPage.getTotal());
    }

    /**
     * 删除记录
     *
     * @param ids id
     */
    @Override
    public void deleteRecords(List<Long> ids) {

    }

    /**
     * 导出预警信息
     *
     * @param warningInfoExportRequest 警告信息出口要求
     * @return {@link Object}
     */
    @Override
    public Result<UploadVO> exportWarningInfo(List<WarningInfoExportRequest> warningInfoExportRequest) {
        BatchSearchGrpcRequest.Builder builder = BatchSearchGrpcRequest.newBuilder();
        for (WarningInfoExportRequest infoExportRequest : warningInfoExportRequest) {
            infoExportRequest.setPlatform(infoExportRequest.getPlatform().toLowerCase());
            Message message = ProtoJsonUtil.toProtoMessage(PlatformFieldGrpcData.newBuilder(), JSON.toJSONString(infoExportRequest));
            builder.addBatchSearchRequest((PlatformFieldGrpcData)message);
        }
        BatchSearchGrpcResponse batchSearchGrpcResponse = searchServiceBlockingStub.batchSearch(builder.build());
        List<SearchDetailGrpcResponse> responseList = batchSearchGrpcResponse.getListList();
        List<WarningInfoExportEntity> exportEntityList = responseList.stream().map(searchDetailGrpcResponse -> ProtoJsonUtil.toJava(searchDetailGrpcResponse, WarningInfoExportEntity.class)).collect(Collectors.toList());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, WarningInfoExportEntity.class).autoCloseStream(true).excelType(ExcelTypeEnum.XLSX).sheet().doWrite(exportEntityList);
        MultipartFile multipartFile = FileUtil.toMultipartFile(outputStream);
        Result<UploadVO> uploadVOResult = ossFeignClient.uploadFile(multipartFile);
        log.info("导出完成，oss文件存储结果： {}", uploadVOResult);
        if(Objects.equals(CommonEnum.SUCCESS.getCode(), uploadVOResult.getCode())){
            //保存记录
            WarningExport warningExport = new WarningExport();
            warningExport.setExportUserId(RequestHolderUtil.getUserId());
            warningExport.setExportDescription(String.format("【素材导出】%s条", warningInfoExportRequest.size()));
            warningExport.setExportTime(LocalDateTime.now());
            warningExport.setExportType(WarningExportTypeEnum.MATERIAL.getCode());
            warningExport.setExportDocumentId(uploadVOResult.getData().getName());
            warningExport.setExportDocumentType(WarningExportDocumentTypeEnum.EXCEL.getCode());
            warningExport.setExportDownloadStatus(WarningExportDownloadStateEnum.EXPORTED.getCode());
            warningExport.setCreateTime(LocalDateTime.now());
            boolean save = this.save(warningExport);
            log.info("保存导出记录是否成功：{}", save);
        }
        return uploadVOResult;
    }
}




